package com.book.lizhi.ui;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import cn.waps.AdInfo;
import cn.waps.AppConnect;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.book.lizhi.AppApplication;
import com.book.lizhi.BaseActivity;
import com.book.lizhi.R;
import com.book.lizhi.adapter.AppAdapter;
import com.book.lizhi.constants.Constants;
import com.book.lizhi.model.AdModel;
import com.book.lizhi.util.AppLog;
import com.book.lizhi.widget.HttpAsyncLayout;
import com.book.lizhi.widget.HttpAsyncLayout.OnHttpAsyncListner;

public class AdvActivity extends BaseActivity {
	private static final int DEFAULT_TRY_TIME = 4;
	private HttpAsyncLayout mAsyncLayout;
	private ListView mAdListView;

	private List<?> mAdInfos;
	private List<AdModel> mAdModels;

	private int tryTime = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_adv);
		Toolbar toolbar = (Toolbar) findViewById(R.id.toobar);
		setSupportActionBar(toolbar);

		ActionBar actionBar = getSupportActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setTitle("精品应用推荐");

		mAsyncLayout = (HttpAsyncLayout) findViewById(R.id.http_async_layout);

		LinearLayout layout = (LinearLayout) findViewById(R.id.ad_layout);
		AppConnect.getInstance(AdvActivity.this).showBannerAd(AdvActivity.this, layout);

		mAdListView = (ListView) findViewById(R.id.adv_listview);
//		if (Util.getBooleanBySharePreference(Constants.SHOW_BOOK)) {
//			View baiduView = View.inflate(getApplicationContext(), R.layout.baidu_sb_ad, null);
//			((TextView) baiduView.findViewById(R.id.include_1).findViewById(R.id.adv_name)).setText("百度手机助手");
//			((TextView) baiduView.findViewById(R.id.include_2).findViewById(R.id.adv_name)).setText("91助手");
//			((TextView) baiduView.findViewById(R.id.include_3).findViewById(R.id.adv_name)).setText("安卓市场");
//			((ImageView) baiduView.findViewById(R.id.include_1).findViewById(R.id.adv_icon)).setImageResource(R.drawable.baidu_icon);
//			((ImageView) baiduView.findViewById(R.id.include_2).findViewById(R.id.adv_icon)).setImageResource(R.drawable.icon_91);
//			((ImageView) baiduView.findViewById(R.id.include_3).findViewById(R.id.adv_icon)).setImageResource(R.drawable.android_icon);
//			mAdListView.addHeaderView(baiduView);
//		}

		mAdListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Object object = parent.getAdapter().getItem(position);
				if (object instanceof AdInfo) {
					AppApplication.instance.adInfo = (AdInfo) mAdInfos.get(position);
					startActivity(new Intent(getApplicationContext(), AdDetailActivity.class));
				}
			}

		});

		mAsyncLayout.setOnHttpAsyncListner(new OnHttpAsyncListner() {

			@Override
			public void onSuccessListener(String url, String response) {
				if (mAdInfos != null && mAdInfos.size() > 0) {

					// List<?> adInfos = AppConnect.getInstance(getApplicationContext()).getAdInfoList();
					// if (adInfos == null || adInfos.size() < 1) {
					// return;
					// }
					// AdInfo adInfo = (AdInfo) adInfos.get(0);
					//
					// NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
					// RemoteViews reViews = new RemoteViews(getPackageName(), R.layout.adv_item_layout);
					// reViews.setImageViewBitmap(R.id.adv_icon, adInfo.getAdIcon());
					// reViews.setTextViewText(R.id.adv_name, adInfo.getAdName());
					// reViews.setTextViewText(R.id.adv_des, adInfo.getAdText());
					// reViews.setTextViewText(R.id.adv_text, adInfo.getAction());
					//
					// Notification notification = new Notification(R.drawable.ic_launcher, "", System.currentTimeMillis());
					// notification.when = System.currentTimeMillis();
					// notification.defaults = Notification.DEFAULT_ALL;
					// notification.flags = Notification.FLAG_AUTO_CANCEL;
					// notification.contentView = reViews;
					//
					// Intent intent = null;
					// // try {
					// intent = new Intent(AdvActivity.this,DownloadIntentService.class);
					// // } catch (ClassNotFoundException e) {
					// // e.printStackTrace();
					// // }
					// intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
					// AppLog.e("ID:"+adInfo.getAdId());
					// intent.putExtra(DownloadIntentService.EXTRA_PARAM, adInfo.getAdId());
					// intent.putExtra("id", "id");
					// PendingIntent pendingIntent = PendingIntent.getService(AdvActivity.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
					// notification.flags |= Notification.FLAG_ONGOING_EVENT;
					// notification.contentIntent=pendingIntent;
					// mNotifyManager.notify(R.string.app_name, notification);

					mAdListView.setAdapter(new AdvAdpater(getApplicationContext(), mAdInfos));
				} else {
					AppConnect.getInstance(getApplicationContext()).showAppOffers(AdvActivity.this);
				}
			}

			@Override
			public void onRefreshListener() {
				AppConnect.getInstance(getApplicationContext()).showAppOffers(AdvActivity.this);
			}

			@Override
			public void onErrorListener(VolleyError error) {
				AppLog.e(error.toString());
				// mAsyncLayout.showNoDataError();
				mAsyncLayout.showCustomError("壮士，点击按钮也可以获取积分的!!!", "点我获取积分");
				AppConnect.getInstance(getApplicationContext()).showAppOffers(AdvActivity.this);
			}
		});

		mAdInfos = AppConnect.getInstance(this).getAdInfoList();

		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {
				while (mAdInfos == null && tryTime < DEFAULT_TRY_TIME) {
					try {
						Thread.sleep(100);
					} catch (final InterruptedException e) {
						e.printStackTrace();
						return false;
					}
					tryTime++;
					mAdInfos = AppConnect.getInstance(AdvActivity.this).getAdInfoList();
				}
				tryTime = 0;
				if (mAdInfos == null || mAdInfos.size() == 0) {
					return false;
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				if (result) {
					mAsyncLayout.onResponse(false, null, JSON.toJSONString(mAdInfos));
				} else {
					mAsyncLayout.onErrorResponse(new VolleyError());
				}
			};
		}.execute();
		mAsyncLayout.onHttpStart();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == android.R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	class TopAdvAdapter extends AppAdapter {

		public TopAdvAdapter(Context context, List<?> list) {
			super(context, list);
		}

		@Override
		public View getView(final int position, View convertView, Context context) {

			AdModel model = mAdModels.get(position);
			NetworkImageView imageView = new NetworkImageView(context);
			imageView.setScaleType(ScaleType.FIT_XY);
			imageView.setImageUrl(model.image_url, AppApplication.instance.imageLoader);
			imageView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (mAdModels == null || mAdModels.size() == 0) {
						return;
					}

					AdModel adModel = mAdModels.get(position);
					Intent intent = new Intent(getApplicationContext(), WebViewActivity.class);
					intent.putExtra(Constants.TITLE, "详情");
					intent.putExtra(Constants.SOURCE_URL, adModel.url);
					startActivity(intent);
				}
			});
			return imageView;

		}

	}

	class AdvAdpater extends AppAdapter {

		public AdvAdpater(Context context, List<?> list) {
			super(context, list);
		}

		@Override
		public View getView(int position, View convertView, Context context) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = View.inflate(getApplicationContext(), R.layout.adv_item_layout, null);
				holder = new ViewHolder();
				holder.downloadBtn = (Button) convertView.findViewById(R.id.btn_appstore_button);
				holder.iconView = (ImageView) convertView.findViewById(R.id.adv_icon);
				holder.nameView = (TextView) convertView.findViewById(R.id.adv_name);
				holder.desView = (TextView) convertView.findViewById(R.id.adv_des);
				holder.textView = (TextView) convertView.findViewById(R.id.adv_text);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			final AdInfo adInfo = (AdInfo) mAdInfos.get(position);
			holder.iconView.setImageBitmap(adInfo.getAdIcon());
			holder.nameView.setText(adInfo.getAdName());
			holder.desView.setText(adInfo.getAdText());
			holder.textView.setText(adInfo.getAction());

			holder.downloadBtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					AppConnect.getInstance(getApplicationContext()).downloadAd(getApplicationContext(), adInfo.getAdId());
				}
			});

			return convertView;
		}

	}

	static class ViewHolder {
		Button downloadBtn;
		ImageView iconView;
		TextView nameView;
		TextView desView;
		TextView textView;
	}
}
